package com.cn.springcloudwechat.serviceImpl.articleAndMenu;


import com.cn.springcloudwechat.common.mybatis.Page;
import com.cn.springcloudwechat.mapper.mapper.articleAndMenu.*;
import com.cn.springcloudwechat.mapper.mapper.attachment.YmAttachmentRelevanceMapper;
import com.cn.springcloudwechat.model.articleAndMenu.YmActivityArticle;
import com.cn.springcloudwechat.model.articleAndMenu.YmArticle;
import com.cn.springcloudwechat.model.articleAndMenu.YmArticleExpand;
import com.cn.springcloudwechat.model.articleAndMenu.YmScrollArticle;
import com.cn.springcloudwechat.model.attachment.YmAttachmentRelevance;
import com.cn.springcloudwechat.model.enumerate.YmActivityState;
import com.cn.springcloudwechat.model.enumerate.YmArticleType;
import com.cn.springcloudwechat.service.articleAndMenu.YmArticleService;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: Administrator
 * @create: 2018/7/17 17:25
 */
@Service("ymArticleServiceImpl")
public class YmArticleServiceImpl implements YmArticleService {
    @Autowired
    YmArticleMapper ymArticleMapper;

    @Autowired
    YmScrollArticleMapper ymScrollArticleMapper;

    @Autowired
    YmMenuTagMapper ymMenuTagMapper;

    @Autowired
    YmArticleExpandMapper ymArticleExpandMapper;

    @Autowired
    YmActivityArticleMapper ymActivityArticleMapper;

    @Autowired
    YmAttachmentRelevanceMapper ymAttachmentRelevanceMapper;
    /**
     * 业务类型1 文章
     */
    private static final String RELEVANCE_TPYE_ID_ARTICLE = "1";
    /**
     *  业务类型8 轮播图
     */
    private static final String RELEVANCE_TPYE_ID_SCROLL_ARTICLE = "8";

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long insertArticle(YmArticle record) {
        long articleId = ymArticleMapper.insertSelective(record);
      //  insterYmAttachmentRelevance(record.getArticleId(), RELEVANCE_TPYE_ID_ARTICLE, attachmentId);
        return record.getArticleId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict("getArticleByArticleId")
    public int updateArticle(YmArticle record) {
     //   updateAttachmentRelevanceState(record.getArticleId(),RELEVANCE_TPYE_ID_ARTICLE,newAttachmentId);
        //文章更新
    return   ymArticleMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public Map<String, Object> getRecommendMenuArticle() {
        Map<String, Object> resultMap = new HashMap<String, Object>(4);
        Page<YmArticle> page=new Page<YmArticle>();
        //获取热门文章
        List<YmArticle> hotArticlesList = ymArticleMapper.getArticles(YmArticleType.HOTARTICLES.getKey(),page);
        //获取精选文章
        List<YmArticle> featuredArticlesList = ymArticleMapper.getArticles(YmArticleType.FEATUREDARTICLES.getKey(),page);
        //获取推荐文章
        List<YmArticle> recommendedArticlesList = ymArticleMapper.getArticles(YmArticleType.RECOMMENDEDARTICLES.getKey(),page);
        //最新文章
        List<YmArticle> newestArticlesList = ymArticleMapper.getArticles(YmArticleType.NEWEST.getKey(),page);
        resultMap.put("hotArticles", hotArticlesList);
        resultMap.put("featuredArticles", featuredArticlesList);
        resultMap.put("recommendedArticles", recommendedArticlesList);
        resultMap.put("newestArticles", newestArticlesList);
        return resultMap;
    }

    @Override
    public Page<YmArticle> getYmArticle(Integer articleType,Page<YmArticle> page) {
        switch (articleType) {
            case 1:
                page.setResults(ymArticleMapper.getArticles(YmArticleType.HOTARTICLES.getKey(),page));
                return page;
            case 2:
                page.setResults(ymArticleMapper.getArticles(YmArticleType.FEATUREDARTICLES.getKey(),page));
                return page;
            case 3:
                page.setResults(ymArticleMapper.getArticles(YmArticleType.RECOMMENDEDARTICLES.getKey(),page));
                return page;
            case 4:
                page.setResults(ymArticleMapper.getArticles(YmArticleType.NEWEST.getKey(),page));
                return page;
            default:
                throw new IllegalArgumentException();
        }
    }

    @Override
    public List<YmArticle> getYmArticleNoPage(Integer articleType,Page<YmArticle> page) {
        switch (articleType) {
            case 1:
                return ymArticleMapper.getArticles(YmArticleType.HOTARTICLES.getKey(),page);
            case 2:
                return ymArticleMapper.getArticles(YmArticleType.FEATUREDARTICLES.getKey(),page);
            case 3:
                return ymArticleMapper.getArticles(YmArticleType.RECOMMENDEDARTICLES.getKey(),page);
            case 4:
                return ymArticleMapper.getArticles(YmArticleType.NEWEST.getKey(),page);
            default:
                throw new IllegalArgumentException();
        }
    }

    @Override
    @Cacheable("getScrollArticle")
    public List<YmScrollArticle> getScrollArticle(Integer scrollType) {
        //获取轮播文章
        return ymScrollArticleMapper.getScrollArticle(scrollType);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict("getScrollArticle")
    public Long insertScrollArticle(YmScrollArticle ymScrollArticle) {
        long scrollArticleId = ymScrollArticleMapper.insertSelective(ymScrollArticle);
      //  insterYmAttachmentRelevance(ymScrollArticle.getScrollArticleId(), RELEVANCE_TPYE_ID_SCROLL_ARTICLE, attachmentId);
        return ymScrollArticle.getScrollArticleId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict("getScrollArticle")
    public int updateScrollArticle(YmScrollArticle ymScrollArticle) {
     //   updateAttachmentRelevanceState(ymScrollArticle.getScrollArticleId(),RELEVANCE_TPYE_ID_SCROLL_ARTICLE,attachmentId);
    return  ymScrollArticleMapper.updateByPrimaryKeySelective(ymScrollArticle);
    }


    @Override
    public Page<YmArticle> getMenuArticle(Long menuTagId,Page<YmArticle> page) {
        //menuTagId为0 查询公告
        List<Long> childInt = ymMenuTagMapper.getChildMenuId(menuTagId);
        List<Long> allChildeMenuIdList = childInt;
        getChildMenuIdRecursion(childInt, allChildeMenuIdList);
        if (childInt.size() == 0) {
            allChildeMenuIdList.add(menuTagId);
        }
        page.setResults(ymArticleMapper.getArticlesByMenuId(allChildeMenuIdList,page));
        return page;
    }

    @Override
    @Cacheable("getArticleExpandData")
    public YmArticleExpand getArticleExpandData(Long articleId) {
        return ymArticleExpandMapper.getArticleExpandData(articleId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict("getArticleExpandData")
    public void updateArticleReadNumber(Long articleId) {
        //判断该文章是否是第一次
        YmArticleExpand ymArticleExpand = getArticleExpandData(articleId);
        if (ymArticleExpand == null) {
            //添加阅读数
            ymArticleExpand = new YmArticleExpand();
            ymArticleExpand.setArticleId(articleId);
            ymArticleExpand.setReadNumber(1L);
            ymArticleExpand.setPraiseNumer(0L);
            ymArticleExpandMapper.insertSelective(ymArticleExpand);
        } else {
            ymArticleExpandMapper.updateArticleReadNumber(articleId);
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertSelective(YmActivityArticle record) {
        //TODO 1期无相关功能暂时不和附件表做关联
        ymActivityArticleMapper.insertSelective(record);
    }

    @Override
    public List<YmActivityArticle> getActivityArticle(YmActivityArticle record) {
        List<YmActivityArticle> ymActivityArticleList = ymActivityArticleMapper.getActivityArticle(record);
        for (YmActivityArticle ymActivityArticle : ymActivityArticleList) {
            DateTime startTime = new DateTime(ymActivityArticle.getActivityStartTime());
            DateTime endTime = new DateTime(ymActivityArticle.getActivityEndTime());
            DateTime today = new DateTime();
            if (startTime.isAfter(today)) {
                //活动未开始
                ymActivityArticle.setActivityState(YmActivityState.NOTSTARTED.getKey());
            } else if (endTime.isBefore(today)) {
                //活动已结束
                ymActivityArticle.setActivityState(YmActivityState.UNDERWAY.getKey());
            } else {
                //活动进行中
                ymActivityArticle.setActivityState(YmActivityState.CLOSURE.getKey());
            }
        }
        return ymActivityArticleList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateActivityArticle(YmActivityArticle record) {
        ymActivityArticleMapper.updateActivityArticle(record);
    }

    @Override
    @Cacheable("getArticleByArticleId")
    public YmArticle selectByPrimaryKey(Long articleId) {
        return ymArticleMapper.selectByPrimaryKey(articleId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateArticleState(List<Long> articleId, short state) {
        ymArticleMapper.updateArticleState(articleId, state);
    }

    @Override
    public Page<Object> getArticlesParameter(YmArticle ymArticle, Page<Object> page) {
        List<Object> ymArticles = ymArticleMapper.getArticlesParameter(ymArticle, page);
        page.setResults(ymArticles);
        return page;
    }

    /**
     * 添加附件关联关系
     *
     * @param relevanceId
     * @param relevanceTpyeId
     * @param attachmentId
     */
    @Override
    public void insterYmAttachmentRelevance(long relevanceId, String relevanceTpyeId, long attachmentId) {
        YmAttachmentRelevance ymAttachmentRelevance = new YmAttachmentRelevance();
        ymAttachmentRelevance.setAttachmentId(attachmentId);
        ymAttachmentRelevance.setRelevanceId(relevanceId);
        ymAttachmentRelevance.setRelevanceTpyeId(relevanceTpyeId);
        ymAttachmentRelevance.setState((short) 1);
        ymAttachmentRelevanceMapper.insertSelective(ymAttachmentRelevance);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateScollArticleState(List<Long> scollArticleId, short state) {
        ymScrollArticleMapper.updateScollArticleId(scollArticleId,state);
    }

    @Override
    public Page<Object> getScrollArticleByParameter(YmScrollArticle record, Page<Object> page) {
         List<Object> ymScrollArticles  =ymScrollArticleMapper.getScrollArticleByParameter(record,page);
        page.setResults(ymScrollArticles);
        return page;
    }

    /**
     * 递归子集菜单
     *
     * @param resultInt
     * @param allChildeMenuIdList
     */
    private void getChildMenuIdRecursion(List<Long> resultInt, List<Long> allChildeMenuIdList) {
        if (resultInt.size() > 0) {
            for (Long childId : resultInt) {
                List<Long> childIdList = ymMenuTagMapper.getChildMenuId(childId);
                for (Long grandsonId : childIdList) {
                    allChildeMenuIdList.add(grandsonId);
                    getChildMenuIdRecursion(childIdList, allChildeMenuIdList);
                }
            }
        }
    }

    /**
     * 修改文章关联关系
     * @param relevanceId
     * @param relevanceType
     * @param newAttachmentId
     */
    private void updateAttachmentRelevanceState(long relevanceId,String relevanceType,Long newAttachmentId){
        if (null != newAttachmentId && newAttachmentId != 0) {
            //修改原文章关联关系
            ymAttachmentRelevanceMapper.updateAttachmentRelevanceState(relevanceId, relevanceType);
            //添加文章和新附件的关联关系
            insterYmAttachmentRelevance(relevanceId, relevanceType, newAttachmentId);
        }
    }
}
